import axios from 'axios';
import Qs from 'qs';
import VueAxios from 'vue-axios';
import store from '@/util/store';
import * as types from '@/util/types';
import router from '@/router';
import Vue from "vue";
import { Message } from 'element-ui';

Vue.prototype.$message = Message;

const axios_instance = axios.create({
    transformRequest: [function (data) {
        data = Qs.stringify(data);
        return data;
    }],
    headers:{'Content-Type':'application/x-www-form-urlencoded'}
});

// axios 配置
axios_instance.defaults.timeout = 5000;

// http request 拦截器
axios_instance.interceptors.request.use(
    config => {
        if (store.state.token) {
            config.headers.Authorization = `token ${store.state.token}`
        }
        return config;
    },
    err => {
        return Promise.reject(err);
    },
);

// http response 拦截器
axios_instance.interceptors.response.use(
    response => {
        if(response.data.code!==200 && response.data.message){
            Message({message:response.data.message,type:"warning"});
        }
        return response

    },
    error => {
        if (error.response) {
            switch (error.response.status) {
                case 401:
                    // 401 清除token信息并跳转到登录页面
                    store.commit(types.LOGOUT)
                    // 只有在当前路由不是登录页面才跳转
                    router.currentRoute.path !== 'login' &&
                    router.replace({
                        path: 'login',
                        query: {redirect: router.currentRoute.path},
                    })
                    break
                case 403:
                    Message({message:'拒绝访问！',type:"error"});
                    break;
                case 404:
                    Message({message:'请求的路径不存在！',type:"error"});
                    break
                case 500:
                    Message({message:'服务器开小差了！',type:"error"});
                    break
            }
        }
        // console.log(JSON.stringify(error));//console : Error: Request failed with status code 402
        return Promise.reject(error.response.data);
    },
);

Vue.use(VueAxios, axios_instance);
export default axios;